<script lang="ts" setup>
  import { User } from '@/types/user';
  import { computed, onMounted, ref } from 'vue';
  import { addPlayersToEnrollType, getPlayerNotEnrollType } from '@/api/game';
  import { Message } from '@arco-design/web-vue';

  const props = defineProps<{
    gameId: string;
    typeId: number;
  }>();

  const emit = defineEmits(['close']);

  const loading = ref(false);
  const searchStr = ref('');
  const list = ref<User[]>([]);

  const filterList = computed(() => {
    if (searchStr.value) {
      return list.value.filter((i) => i.nickname.indexOf(searchStr.value) >= 0);
    }
    return list.value;
  });

  const getData = async () => {
    try {
      loading.value = true;
      const res = await getPlayerNotEnrollType(props.gameId);
      list.value = res.data.data;
    } finally {
      loading.value = false;
    }
  };

  const selectedKeys = ref<string[]>([]);
  const saving = ref(false);
  const handleSubmit = async () => {
    if (selectedKeys.value.length === 0) {
      Message.warning('请选择要添加的球员');
      return;
    }
    try {
      saving.value = true;
      await addPlayersToEnrollType(
        props.gameId,
        props.typeId,
        selectedKeys.value
      );
      emit('close', true);
    } finally {
      saving.value = false;
    }
  };

  onMounted(() => {
    getData();
  });
</script>

<template>
  <a-drawer
    title="添加球员"
    :width="500"
    visible
    :ok-loading="saving"
    @cancel="emit('close', false)"
    @before-ok="handleSubmit"
  >
    <a-input v-model="searchStr" placeholder="搜索球员姓名" />

    <div style="height: 12px"></div>
    <a-table
      v-model:selectedKeys="selectedKeys"
      :loading="loading"
      :data="filterList"
      :pagination="false"
      size="small"
      :bordered="{ cell: true }"
      row-key="id"
      :row-selection="{
        type: 'checkbox',
        showCheckedAll: true,
      }"
    >
      <template #columns>
        <a-table-column title="姓名" data-index="nickname" />
        <a-table-column title="性别" data-index="sex">
          <template #cell="{ record }">{{ record.sex ? '男' : '女' }}</template>
        </a-table-column>
        <a-table-column title="电话" data-index="phone" />
      </template>
    </a-table>
  </a-drawer>
</template>
